An enthusiastic, adaptive, and fast-learning person with a broad and acute interest in the discovery of new innovative drugs, I particularly enjoy collaborating with scientists from different disciplines to develop new skills and solve new challenges.
In LINQ, the GroupBy operator is used to grouping the list/collection items based on the specified key-value, it returns a collection of IGrouping<Key, Values>. The Groupby method in LINQ is the same as the SQL group by clause.
Syntax
IEnumerable<IGrouping<key, value>> group = collection.GroupBy( condition)
Example
using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
List<Student> students = new List<Student>(){
new Student() { StudentId = 1, Name = 'Ashu', Marks = 500 },
new Student() { StudentId = 2, Name = 'Shyam', Marks = 500 },
new Student() { StudentId = 3, Name = 'Shriyam', Marks = 400 },
new Student() { StudentId = 4, Name = 'Sunny', Marks = 550 },
new Student() { StudentId = 5, Name = 'Ram', Marks = 600 },
new Student() { StudentId = 6, Name = 'Krishna', Marks = 550 },
new Student() { StudentId = 7, Name = 'Anupam', Marks = 550 }
} ;
List<IGrouping<int, Student>> list = students.GroupBy(stu => stu.Marks).ToList();
list.ForEach( evt => {
Console.WriteLine('\nkey : ' + evt.Key+' No of times : ' + evt.Count() + '\n');
Console.WriteLine('{0,-10} {1,4} {2,5}','Name','ID','Marks');
foreach(Student student in evt){
Console.WriteLine('{0,-10} {1,4} {2,5}',student.Name, student.StudentId,student.Marks);
}
}) ;
Console.ReadLine();
}
}
class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public int Marks { get; set; }
}
Output
Key : 500 No of times : 2
Name ID Marks
Ashu 1 500
Shyam 2 500
Key : 400 No of times : 1
Name ID Marks
Shriyam 3 400
Key : 550 No of times : 3
Name ID Marks
Sunny 4 550
Krishna 6 550
Anupam 7 550
Key : 600 No of times : 1 Name ID Marks Ram 5 600
Liked By
Write Answer
How to use LINQ GroupBy Method in C#?
Join MindStick Community
You have need login or register for voting of answers or question.
Ravi Vishwakarma
27-Sep-2021In LINQ, the GroupBy operator is used to grouping the list/collection items based on the specified key-value, it returns a collection of IGrouping<Key, Values>. The Groupby method in LINQ is the same as the SQL group by clause.
Syntax
Example
Output